package it.asvp.asvp_portal.data.entity.member;

import it.asvp.asvp_portal.asvp_util.enumerative.RoleName;
import it.asvp.asvp_portal.data.entity.domain.BaseEntity;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@SuppressWarnings("serial")
@Entity
@Table(name = "role", catalog = "asvp_db", uniqueConstraints = @UniqueConstraint(columnNames = "name"))
public class Role extends BaseEntity {

  @Column(name = "name", unique = true, nullable = false, length = 50)
  @Enumerated(EnumType.STRING)
  private RoleName roleName;

  @Column(name = "description", nullable = false, length = 500)
  private String   description;

  public Role() {
  }

  public Role(RoleName name, String description, Date createdOn, Date lastUpdate) {
    this.roleName = name;
    this.description = description;
    this.createdOn = createdOn;
    this.lastUpdate = lastUpdate;
  }

  public RoleName getRoleName() {
    return roleName;
  }

  public void setRoleName(RoleName roleName) {
    this.roleName = roleName;
  }

  public String getDescription() {
    return this.description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public boolean equals(Role role) {
    return (this.roleName.equals(role.getRoleName()));
  }

  // FIXME: controllare il funzionamento del metodo compareTo per tipi
  // enumerativi
  public int compareTo(Role role) {
    if (role.getRoleName().compareTo(this.getRoleName()) == 0) {
      return 0;
    } else if (role.getRoleName().compareTo(this.getRoleName()) == 1) {
      return 1;
    } else {
      return -1;
    }
  }

  public static Role getMax(Set<Role> roles) {
    if (roles.size() == 0) {
      return null;
    }
    Iterator<Role> it = roles.iterator();
    if (roles.size() == 1) {
      return it.next();
    }
    Role max = it.next();
    while (it.hasNext()) {
      Role item = it.next();
      if (item.compareTo(max) >= 0) {
        max = item;
      }
    }
    return max;
  }

}
